<template>
    <div>
        <!--面包屑导航区域-->
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/adminIndex' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>采购员列表</el-breadcrumb-item>
        </el-breadcrumb>

        <!--卡片视图区域-->
        <el-card>
            <!--搜索与添加区域-->
            <el-row :gutter="20">
                <el-col :span="7">
                    <el-input placeholder="请输入查询信息" v-model="queryInfo.query" clearable @clear="getBuyerList">
                        <el-button slot="append" icon="el-icon-search" @click="getBuyerList"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" @click="addDialogVisible = true">添加采购员</el-button>
                </el-col>
            </el-row>

            <!--用户列表区域-->
            <el-table :data="buyerList" border stripe>
                <el-table-column type="index"></el-table-column>
                <el-table-column label="账号" prop="account"></el-table-column>
                <el-table-column label="名称">
                    <template slot-scope="scope">
                        <el-tag size="medium">{{ scope.row.buyerName }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="地址" prop="buyerAddress" :show-overflow-tooltip='true'></el-table-column>
                <el-table-column label="联系方式" prop="contact"></el-table-column>
                <el-table-column label="金额" prop="money"></el-table-column>
                <el-table-column label="状态">
                    <template slot-scope="scope">
                        <el-switch v-model="scope.row.buyerState" @change="userStateChanged(scope.row)">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-tooltip effect="dark" content="修改" placement="top" :enterable="false">
                            <el-button type="primary" size="mini" icon="el-icon-edit"
                                       @click="showEditDialog(scope.row.account)"></el-button>
                        </el-tooltip>
                        <el-tooltip effect="dark" content="充值" placement="top" :enterable="false">
                            <el-button type="success" size="mini"
                                       @click="addMoney(scope.row.buyerId)">$
                            </el-button>
                        </el-tooltip>
                        <el-tooltip effect="dark" content="删除" placement="top" :enterable="false">
                            <el-button type="danger" size="mini" icon="el-icon-delete"
                                       @click="removeBuyer(scope.row.account)"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>

            <!--分页区域-->
            <el-pagination
                    background
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="queryInfo.current"
                    :page-sizes="[2, 3, 5, 10]"
                    :page-size="queryInfo.pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </el-card>

        <!--添加采购员的对话框-->
        <el-dialog title="添加采购员" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
            <!--内容主体区域-->
            <el-form ref="addBuyerRef" :model="addBuyer" :rules="addBuyerRules" label-width="70px">
                <el-form-item label="账号" prop="account">
                    <el-input v-model="addBuyer.account"></el-input>
                </el-form-item>
                <el-form-item label="姓名" prop="buyerName">
                    <el-input v-model="addBuyer.buyerName"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="buyerPassword">
                    <el-input v-model="addBuyer.buyerPassword" type="password" show-password></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="contact">
                    <el-input v-model="addBuyer.contact"></el-input>
                </el-form-item>
                <el-form-item label="金额" prop="money">
                    <el-input v-model.number="addBuyer.money"></el-input>
                </el-form-item>
            </el-form>
            <!--底部区域-->
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addOneBuyer">确 定</el-button>
            </span>
        </el-dialog>
        <!--充值对话框-->
        <el-dialog title="金额充值" :visible.sync="addMoneyDialogVisible" width="50%" @close="addMoneyDialogClosed">
            <!--内容主体区域-->
            <el-form ref="addMoneyRef" label-width="70px">
                <el-form-item label="金额充值">
                    <el-input v-model.number="money"></el-input>
                </el-form-item>
            </el-form>
            <!--底部区域-->
            <span slot="footer" class="dialog-footer">
                <el-button @click="addMoneyDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addMoneyToBuyer">确 定</el-button>
            </span>
        </el-dialog>
        <!--修改采购员的对话框-->
        <el-dialog title="修改采购员" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
            <el-form ref="editBuyerRef" :model="editBuyer" :rules="editBuyerRules" label-width="70px">
                <el-form-item label="账号">
                    <el-input v-model="editBuyer.account" disabled></el-input>
                </el-form-item>
                <el-form-item label="姓名" prop="buyerName">
                    <el-input v-model="editBuyer.buyerName"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="buyerPassword">
                    <el-input v-model="editBuyer.buyerPassword" type="password"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="contact">
                    <el-input v-model="editBuyer.contact"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editOneBuyer">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script scoped>
    export default {
        data() {
            // 验证手机号的规则
            var checkMobile = (rule, value, callback) => {
                // 验证手机号的正则表达式
                const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
                if (regMobile.test(value)) {
                    return callback()
                }
                callback(new Error('请输入合法的手机号'))
            }
            return {
                // 获取用户列表的参数对象
                queryInfo: {
                    query: '',
                    // 当前的页数
                    current: 1,
                    // 当前每页显示多少条数据
                    pageSize: 7
                },
                buyerList: [],
                total: 0,
                //控制添加用户对话框的显示与隐藏
                addDialogVisible: false,
                //添加上报员的表单数据
                addBuyer: {
                    account: '',
                    buyerName: '',
                    buyerPassword: '',
                    buyerAddress: '',
                    contact: '',
                    money: ''
                },
                //添加采购员的验证规则对象
                addBuyerRules: {
                    account: [
                        {required: true, message: '请输入账号', trigger: 'blur'},
                        {min: 3, max: 18, message: '账号的长度在3~18个字符之间', trigger: 'blur'},
                    ],
                    buyerName: [
                        {required: true, message: '请输入姓名', trigger: 'blur'}
                    ],
                    buyerPassword: [
                        {required: true, message: '请输入密码', trigger: 'blur'},
                        {min: 6, max: 15, message: '密码的长度在6~15个字符之间', trigger: 'blur'}
                    ],
                    contact: [
                        {required: true, message: '请输入手机号', trigger: 'blur'},
                        {validator: checkMobile, trigger: 'blur'}
                    ]
                },
                //控制修改采购员对话框的显示与隐藏
                editDialogVisible: false,
                //查询到的采购员信息对象
                editBuyer: {},
                //修改表单验证规则对象
                editBuyerRules: {
                    buyerName: [
                        {required: true, message: '请输入姓名', trigger: 'blur'}
                    ],
                    buyerPassword: [
                        {required: true, message: '请输入密码', trigger: 'blur'},
                        {min: 6, max: 15, message: '密码的长度在6~15个字符之间', trigger: 'blur'}
                    ],
                    contact: [
                        {required: true, message: '请输入手机号', trigger: 'blur'},
                        {validator: checkMobile, trigger: 'blur'}
                    ]
                },
                addMoneyDialogVisible: false,
                money: '',
                buyerId: ''
            }
        },
        created() {
            this.getBuyerList()
        },
        methods: {
            async getBuyerList() {
                var result = await this.$http.get('user/buyer/selectAll', {params: this.queryInfo})
                if (result.data.status !== 200) {
                    return this.$message.error("获取上报员列表失败！")
                }
                this.buyerList = result.data.data.records
                this.total = result.data.data.total
            },
            //监听pagesize改变的事件
            handleSizeChange(newSize) {
                this.queryInfo.pageSize = newSize
                this.getBuyerList()
                this.queryInfo.pageSize = 7
            },
            //监听页码值改变的事件
            handleCurrentChange(newPage) {
                this.queryInfo.current = newPage
                this.getBuyerList()
                this.queryInfo.current = 1
            },
            // 监听 switch 开关状态的改变
            async userStateChanged(buyerInfo) {
                const result = await this.$http.put(
                    `user/buyer/${buyerInfo.account}/state/${buyerInfo.buyerState}`
                )
                if (result.status !== 200) {
                    buyerInfo.state = !buyerInfo.state
                    return this.$message.error('更新采购员状态失败！')
                }
                this.$message.success('更新采购员状态成功！')
            },
            //监听添加采购员对话框的关闭事件
            addDialogClosed() {
                this.$refs.addBuyerRef.resetFields()
            },
            //点击添加采购员
            addOneBuyer() {
                this.$refs.addBuyerRef.validate(async valid => {
                    if (!valid) return
                    //发起网络请求
                    //检查用户名是否存在
                    var existAccount = await this.$http.get('user/buyer/selectAccount', {
                        params: {
                            account: this.addBuyer.account
                        }
                    })
                    if (existAccount.data.data == "账号已经存在") {
                        this.$message.error('账号已经存在，请重新输入账号！！！')
                        return
                    }
                    const result = await this.$http.post('user/buyer/save', this.addBuyer)
                    if (result.data.status !== 200) {
                        this.$message.error('添加采购员失败！')
                        return
                    }
                    this.$message.success('添加采购员成功！')
                    // 隐藏添加采购员的对话框
                    this.addDialogVisible = false
                    // 重新获取采购员列表数据
                    this.getBuyerList()
                })
            },
            //展示编辑采购员的对话框
            async showEditDialog(account) {
                const result = await this.$http.get('user/buyer/selectOne', {
                    params: {
                        account: account
                    }
                })
                if (result.data.status !== 200) {
                    return this.$message.error('查询采购员信息失败！')
                }
                this.editBuyer = result.data.data
                this.editDialogVisible = true
            },
            //监听修改采购员对话框的关闭事件
            editDialogClosed() {
                this.$refs.editBuyerRef.resetFields()
            },
            //修改采购员信息并提交
            editOneBuyer() {
                this.$refs.editBuyerRef.validate(async valid => {
                    if (!valid) return
                    // 发起修改采购员的数据请求
                    const result = await this.$http.put('user/buyer/update', this.editBuyer)
                    if (result.data.status !== 200) {
                        return this.$message.error('更新采购员信息失败！')
                    }
                    // 关闭对话框
                    this.editDialogVisible = false
                    // 刷新数据列表
                    this.getBuyerList()
                    // 提示修改成功
                    this.$message.success('更新采购员信息成功！')
                })
            },
            //根据账号删除采购员
            async removeBuyer(account) {
                //弹框是否删除
                const confirmResult = await this.$confirm('此操作将永久删除该采购员, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(error => error)
                // 如果用户确认删除，则返回值为字符串 confirm
                // 如果用户取消了删除，则返回值为字符串 cancel
                if (confirmResult !== 'confirm') {
                    return this.$message.info('已取消删除')
                }
                const result = await this.$http.delete('user/buyer/delete', {
                    params: {
                        account: account
                    }
                })
                if (result.data.status !== 200) {
                    return this.$message.error('删除采购员失败！')
                }
                this.$message.success('删除采购员成功！')
                this.getBuyerList()
            },
            async addMoney(buyerId) {
                this.buyerId = buyerId
                this.addMoneyDialogVisible = true
            },
            addMoneyDialogClosed() {
                this.money = ''
            },
            async addMoneyToBuyer() {
                const result = await this.$http.get('user/buyer/addMoney', {
                    params: {
                        buyerId: this.buyerId,
                        money: this.money
                    }
                })
                if (result.data.status !== 200) {
                    return this.$message.error('更新采购员信息失败！')
                }
                this.$message.success('金额充值成功！！！')
                this.addMoneyDialogVisible = false
                this.getBuyerList()
            }
        }
    }
</script>

<style scoped>
    .el-breadcrumb {
        margin-bottom: 15px;
        font-size: 12px;
    }

    .el-card {
        box-shadow: 0 1px 1px rgba(0, 0, 0, 0.15) !important;
    }

    .el-table {
        margin-top: 15px;
        font-size: 12px;
    }

    .el-pagination {
        text-align: right;
        margin-top: 15px;
    }
</style>
